<template>
  <div class="app-container" style="padding:1vh 4vw">
    <el-button type="primary" style="margin: 6vh 2vw;" icon="el-icon-edit" @click="handleAddRole" :size="handleSize()">
      添加角色
    </el-button>

    <div class="tab-container" style="margin: 0 2vw;">
      <el-table :data="rolesList" highlight-current-row fit border :size="handleSize()" style="width:100%;" max-height="800" tooltip-effect="light">
        <el-table-column fixed sortable label="ID" prop="id" min-width="100" max-width="200"/>
        <el-table-column align="center" prop="name" label="角色名" min-width="100" max-width="200" />
        <el-table-column align="header-center" prop="description" label="角色描述" min-width="400" max-width="600" />
        <el-table-column label="操作" align="center" max-width="400" min-width="200">
          <template v-slot="scope">
            <el-button v-show="device() !== 'mobile'" size="mini" @click="handleEdit(scope.row)"  type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button v-show="device() !== 'mobile'" size="mini" type="danger" @click="handleDelete(scope.row)" icon="el-icon-delete">删除</el-button>
            <el-button v-show="device() === 'mobile'" size="mini" @click="handleEdit(scope.row)"  type="primary" icon="el-icon-edit" circle/>
            <el-button v-show="device() === 'mobile'" size="mini" type="danger" @click="handleDelete(scope.row)" icon="el-icon-delete" circle/>
          </template>
        </el-table-column>

        <el-row style="display: flex;justify-content: center;margin-top: 5vh">
          <el-col :xs="18" :sm="12" :md="12" :lg="8" :xl="6" style="display: flex;justify-content: center">
            <el-pagination
              v-show="total>0"
              background
              hide-on-single-page
              :current-page.sync="currentPage"
              :page-size="perPage"
              :pager-count="5"
              layout="prev, pager, next"
              @prev-click="change"
              @next-click="change"
              @current-change="change"
              :total="total">
            </el-pagination>
          </el-col>
        </el-row>
      </el-table>
    </div>

    <el-dialog :visible.sync="dialogVisible" :title="dialogStatus==='edit'?'编辑':'创建'" :fullscreen="device() === 'mobile'">
      <el-form :model="postForm" label-width="70px" :rules="rules" :label-position="device() === 'mobile' ? 'top' : 'left'" :size="handleSize()">
        <el-form-item label="角色名">
          <el-input v-model="postForm.name" :size="handleSize()" style="width: 300px"/>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="postForm.description" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入角色描述" :size="handleSize()" />
        </el-form-item>
        <el-form-item label="模版菜单">
          <el-tree :data="routesData" v-model="permissions" ref="tree" :props="defaultProps" @node-click="handleNodeClick" node-key="path" show-checkbox class="permission-tree" />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false" :size="handleSize()">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()" :size="handleSize()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deepClone } from '@/utils'
import accountRoute from '@/router/modules/account'
import roleRouter from '@/router/modules/role'
import activityRouter from '@/router/modules/activity'
import errorPageRouter from '@/router/modules/errorPage'
import { changePermission, indexPermission } from '@/api/admin/permission'
import { changeRole, deleteRole, indexRole } from '@/api/admin/role'

const defaultRole = {
  id: '',
  name: '',
  description: '',
}

export default {
  data() {
    return {
      currentPage: 0,
      lastPage: 0,
      total: 0,
      perPage: 0,
      dialogStatus: '',
      dialogVisible: false,
      checkStrictly: false,
      permissions: [],
      defaultProps: {
        // children: 'children',
        // label: 'label'
        label: 'name'
      },
      rules: {
        name: [{ required: true, message: '必填', trigger: 'blur' }],
        description: [{ required: true, message: '必填', trigger: 'blur' }],
        routes: [{ required: true, message: '必选', trigger: 'blur' }]
      },
      postForm: Object.assign({}, defaultRole),
      rolesList: [{
        id: 1,
        name: '超级管理员',
        description: '拥有所有查看和操作功能'
      }],
      routes: []
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  created() {
    // 从服务器端获取 路由列表 和 角色列表
    this.currentPage = 1;
    this.getRoutes()
    this.getRoles()
  },
  methods: {
    // 获取 权限列表
    change(e) {
      this.currentPage = e
      this.getRoles()
    },
    // 返回 当前设备类型
    device() {
      return this.$store.state.app.device
    },
    // 根据当前设备类型控制 尺寸
    async getRoles() {
      const res = await indexRole({ page: this.currentPage })
      this.rolesList = res.data.data
      this.currentPage = res.data.currentPage
      this.lastPage = res.data.lastPage
      this.total = res.data.total
      this.perPage = res.data.perPage
    },
    // 分页
    async getRoutes() {
      const res = await indexPermission()
      this.routes = res.data.data
    },
    // 创建数据
    async createData() {
      //返回 点击树数据
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([])
      }
      console.log(this.$refs.tree.setCheckedNodes([]))
      // changeRole({ name: this.postForm.name, description: this.postForm.description }).then(() => {
      //   this.$notify({
      //     title: '成功',
      //     message: '创建成功',
      //     type: 'success',
      //     duration: 2000
      //   })
      //   // 重新获取数据
      //   this.getRoles()
      // })
      // this.loading = false
      // this.dialogVisible = false
    },
    // 修改数据
    updateData() {
      changeRole({ id: this.postForm.id,name: this.postForm.name, description: this.postForm.description }).then(() => {
        this.$notify({
          title: '成功',
          message: '创建成功',
          type: 'success',
          duration: 2000
        })
        // 重新获取数据
        this.getRoles()
      })
      this.loading = false
      this.dialogVisible = false
    },
    // 新增角色
    async handleAddRole() {
      // 清空数据
      this.postForm = Object.assign({}, defaultRole)
      this.dialogStatus = 'create'
      this.dialogVisible = true
    },
    // 编辑角色
    handleEdit(row) {
      //  复制对象
      this.postForm = Object.assign({}, row)
      this.dialogStatus = 'edit'
      this.dialogFormVisible = true
    },
    // 删除角色
    handleDelete(row) {
      this.$confirm('确定删除此活动', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          deleteRole({ id: row.id }).then(async ()=>{
            this.getRoles()
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
        })
        .catch(err => {
          console.error(err)
        })
    },
    // 删除角色
    handleNodeClick(data) {
      console.log(data)
    },
    // 提交角色表单
    handleSize() {
      return this.$store.state.app.device === 'mobile' ? 'mini' : 'medium'
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  //margin-top: 30px;
  //margin-left: 2rem;
  //margin-right: 2rem;
  //border-radius: 15px;
  //box-shadow: 0 1px 4px rgba(0, 0, 0, 0.4);

  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>

<!--data: [{-->
<!--label: '一级 1',-->
<!--children: [{-->
<!--label: '二级 1-1',-->
<!--children: [{-->
<!--label: '三级 1-1-1'-->
<!--}]-->
<!--}]-->
<!--}, {-->
<!--label: '一级 2',-->
<!--children: [{-->
<!--label: '二级 2-1',-->
<!--children: [{-->
<!--label: '三级 2-1-1'-->
<!--}]-->
<!--}, {-->
<!--label: '二级 2-2',-->
<!--children: [{-->
<!--label: '三级 2-2-1'-->
<!--}]-->
<!--}]-->
<!--}, {-->
<!--label: '一级 3',-->
<!--children: [{-->
<!--label: '二级 3-1',-->
<!--children: [{-->
<!--label: '三级 3-1-1'-->
<!--}]-->
<!--}, {-->
<!--label: '二级 3-2',-->
<!--children: [{-->
<!--label: '三级 3-2-1'-->
<!--}]-->
<!--}]-->
<!--}],-->

<!--, {-->
<!--id: 2,-->
<!--name: '管理员',-->
<!--description: '拥有除添加和删除角色外的所有查看和操作功能'-->
<!--}, {-->
<!--id: 3,-->
<!--name: '编辑者',-->
<!--description: '拥有所有查看、添加、删除操作，但只拥有编辑自己创建的数据权限'-->
<!--}, {-->
<!--id: 4,-->
<!--name: '普通用户',-->
<!--description: '只拥有查看权限'-->
<!--}-->
